package org.javaboy.rpc_client.controller;

import org.javaboy.rpc_client.config.RabbitConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/send")
    public String send(String name) {
        //构建一个待发送的消息
        Message msg = MessageBuilder.withBody(name.getBytes()).build();
        //发送消息，返回值就是服务端返回的消息对象
        Message replyMsg = rabbitTemplate.sendAndReceive(RabbitConfig.RPC_EXCHANGE, RabbitConfig.SEND_MSG_QUEUE, msg);
        //获取发送的消息的correlationId，这个correlationId一开始是没有的，当消息发送成功之后，才会有
        String correlationId = msg.getMessageProperties().getCorrelationId();
        String replyCorrelationId = (String) replyMsg.getMessageProperties().getHeader("spring_returned_message_correlation");
        //判断correlationId是否相等，如果相等说明消息发送成功
        if (correlationId.equals(replyCorrelationId)) {
            //获取服务端返回的消息
            String result = new String(replyMsg.getBody());
            return result;
        }
        return "error";
    }
}
